<?php

namespace App\Http\Handler;

use App\Constants\Common\HttpStatusCode;
use App\Foundation\Rbac\UserRBAC;
use Framework\Foundation\Database\FDB;
use Framework\Foundation\Warehouse;
use Framework\MiddlewareRunner;
use Lcobucci\JWT\Token;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\RequestHandlerInterface;
use Psr\Http\Message\ResponseInterface;

/**
 * Class RbacHandler
 * @package App\Http\Handler
 * @link https://www.cnblogs.com/chengege/p/10695713.html
 */
class RestRbacHandler implements RequestHandlerInterface
{
    public function handle(ServerRequestInterface $request): ResponseInterface
    {
        $restDispatchInfo = $request->getAttribute('restDispatchInfo');
        if (empty($restDispatchInfo)) {
            throw new \Exception("权限认证缺失数据");
        }
        /**
         * @var $jwtToken Token;
         */
        $jwtToken = $request->getAttribute('jwtToken');
        if (empty($jwtToken)) {
            throw new \Exception("无权限-缺失token");
        }


        $where['method'] = $restDispatchInfo['3']['action'];
        $where['source'] = $restDispatchInfo['3']['resource'];
        $permissionRet = FDB::from('rbac_permissions')->where($where)->fetch();
        if (empty($permissionRet)) {
            throw new \Exception("无权限");
        }

        $uid = $jwtToken->getClaim('uid');
        $rbac = new UserRBAC();
        $check = $rbac->hasPermission($uid, $permissionRet['permission_id']);
        if (!$check) {
            throw new \Exception("权限认证不通过");
        }

        return MiddlewareRunner::next($request);
    }
}
